package worldinruin.rules.imp;

import worldinruin.core.IPlayer;
import worldinruin.core.ISoldier;
import worldinruin.core.ITile;
import worldinruin.core.ITroop;
import worldinruin.core.IType;
import worldinruin.core.imp.Troop;
import worldinruin.core.imp.buildings.BuildingTypes;
import worldinruin.core.imp.buildings.City;
import worldinruin.core.imp.tilemodels.TileTypes;
import worldinruin.rules.IRules;


public class Rules implements IRules {
	
	private static IRules instance;
	
	/**
	 * Creates a rules object to be used in game.
	 */
	private Rules(){}
	
	/**
	 * Gets a single instance of Rules.
	 * @return Single instance of Rules.
	 */
	public static IRules getInstance() {
		if(instance == null) {
			instance = new Rules();
		}
		return instance;
	}

	@Override
	public BuildingTypes getAvailableBuildings(ITile tile) {
		// TODO Auto-generated method stub
		IType tileType = tile.getTileType();
		BuildingTypes buildingType = null;
		if(tileType == TileTypes.FERTILETILE) {
			buildingType = BuildingTypes.FARM;
		}
		else if(tileType == TileTypes.FORESTTILE) {
			buildingType = BuildingTypes.SAWMILL;
		}
		else if(tileType == TileTypes.GRASSTILE) {
			buildingType = BuildingTypes.BARRACK;
		}
		else if(tileType == TileTypes.IRONTILE) {
			buildingType = BuildingTypes.IRONMINE;
		}
		else if(tileType == TileTypes.STONETILE) {
			buildingType = BuildingTypes.STONEMINE;
		}
		return buildingType;
	}

	@Override
	public ITile[] getPossibleDestinations(Troop troop, ITile dep) {
		// TODO Auto-generated method stub
		ITile troopTile = troop.getPosition();
		int troopSpeed = 1;
		for(ISoldier soldier : troop.getSoldiers()) {
			troopSpeed = Math.min(troopSpeed, soldier.getSpeed());
		}
		
		return null;
	}

	@Override
	public boolean isDefeated(IPlayer p) {
		// TODO Auto-generated method stub
		return !p.getBuildings().contains(new City());
	}


	
	
	

	@Override
	public int calculateSpeed(ITroop t) {
		
		ISoldier[] array = t.getSoldiers().toArray(new ISoldier[0]);
		int min = array[0].getSpeed();
		
		for (ISoldier soldier : array){			
			if (soldier.getSpeed() < min){
				min = soldier.getSpeed();
			}			
		}
		
		return min;
	}

	@Override
	public boolean isPossibleMove(ITile from, ITile to, ITroop troop) {
		return calculateSpeed(troop) >= (Math.abs(from.getColumn() - to.getColumn())
				+ Math.abs(from.getRow() - to.getRow())); 
	}


}
